from sqlalchemy.orm import Session
from sqlalchemy import func

from db.models import CompilationHistory, PlatformStats
from api.schemas.stats import CompilationStats, PlatformDistribution
from loguru import logger

def get_compilation_stats(db: Session) -> CompilationStats:
    """获取编译统计数据"""
    # 总编译次数
    total = db.query(CompilationHistory).count()
    
    # 成功次数
    successful = db.query(CompilationHistory).filter(
        CompilationHistory.status == "success"
    ).count()
    
    # 失败次数
    failed = db.query(CompilationHistory).filter(
        CompilationHistory.status == "failed"
    ).count()
    
    # 总文件数
    total_files = db.query(func.count(CompilationHistory.id)).scalar() or 0
    
    return CompilationStats(
        total=total,
        successful=successful,
        failed=failed,
        total_files=total_files
    )

def get_platform_distribution(db: Session) -> PlatformDistribution:
    """获取平台分布统计"""
    # 确保所有平台都有记录
    platforms = PlatformStats.get_platforms()
    for platform in platforms:
        stats = db.query(PlatformStats).filter(
            PlatformStats.platform == platform
        ).first()
        if not stats:
            db.add(PlatformStats(platform=platform, count=0))
    
    db.commit()
    
    # 获取平台统计
    platform_stats = db.query(PlatformStats).all()
    
    distribution = {
        stat.platform: stat.count for stat in platform_stats
    }
    
    return PlatformDistribution(distribution=distribution)

def update_platform_stats(db: Session, platform: str):
    """更新平台统计数据"""
    stats = db.query(PlatformStats).filter(
        PlatformStats.platform == platform
    ).first()
    
    if not stats:
        stats = PlatformStats(platform=platform, count=1)
        db.add(stats)
    else:
        stats.count += 1
    
    db.commit()
